package com.auth.service;

import com.auth.pojo.dto.SecurityUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * 菜单权限服务
 * 支持动态路由和菜单权限控制
 */
@Slf4j
@Service
public class MenuPermissionService {

    /**
     * 判断当前用户是否有权限访问指定菜单
     *
     * @param menuPermission 菜单权限标识
     * @return 是否有权限
     */
    public boolean hasMenuPermission(String menuPermission) {
        // 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        
        // 获取当前用户
        Object principal = authentication.getPrincipal();
        if (!(principal instanceof SecurityUserDTO)) {
            return false;
        }
        
        SecurityUserDTO userDetails = (SecurityUserDTO) principal;
        
        // admin用户拥有所有权限
        if ("admin".equals(userDetails.getUsername())) {
            return true;
        }
        
        // 检查用户是否有指定菜单权限
        List<Map<String, Object>> menus = userDetails.getMenus();
        if (CollectionUtils.isEmpty(menus)) {
            return false;
        }
        
        // 遍历菜单，检查权限标识
        for (Map<String, Object> menu : menus) {
            String permission = (String) menu.get("permission");
            if (menuPermission.equals(permission) || 
                (permission != null && permission.endsWith(":*") && 
                 menuPermission.startsWith(permission.substring(0, permission.length() - 2)))) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 获取当前用户的菜单列表
     *
     * @return 菜单列表
     */
    public List<Map<String, Object>> getCurrentUserMenus() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        Object principal = authentication.getPrincipal();
        if (!(principal instanceof SecurityUserDTO)) {
            return null;
        }
        
        return ((SecurityUserDTO) principal).getMenus();
    }
}
